/**
 * Copyright (c) 2017-2018, zengjintao (1913188966@qq.com).
 * <p>
 * Licensed under the GNU Lesser General Public License (LGPL) ,Version 3.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.gnu.org/licenses/lgpl-3.0.txt
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.jfast.framework.server;

import java.io.IOException;

import com.jfast.framework.log.Logger;
import com.jfast.framework.web.config.JfastConfigManager;

public abstract class JfastServer implements IServer {

	private boolean isRunning = false;
	
	protected static final Logger logger = Logger.getLogger(JfastServer.class);
	
	protected JfastServerConfig jfastServerConfig;
	
	public JfastServer(){
		this.jfastServerConfig = getJfastServerConfig();
	}

	public boolean isRunning() {
		return isRunning;
	}

	public JfastServerConfig getJfastServerConfig() {
		return JfastConfigManager.createConfigBean(JfastServerConfig.class);
	}
	
	@Override
	public void start()  {
		if(!isRunning){
			isRunning = true;
			try {
				doStart();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}else {
			throw new IllegalStateException("port: " + jfastServerConfig.getPort() + " already in use!");
		}
	}
	@Override
	public void restart() {
		this.stop();
		this.start();
	}
	
	@Override
	public void stop() {
		doReStart();
	}
	
	protected void printSuccesInfo(){
		System.out.println(jfastServerConfig.toString());
		logger.info("server started success,url :http://" +jfastServerConfig.getHost()
		                 +":"+jfastServerConfig.getPort());
	}
	
	protected void printFailInfo(){
		logger.info("server started fail");
	}
	
	public abstract void doStart() throws IOException;
	
	public abstract void doReStart();
	
	//public abstract void addServlet();
}
